'use strict';

const async = require('async');

module.exports = app => {
  app.beforeStart(async () => {
    // 应用会等待这个函数执行完成才启动

    // REDIS 时间过期了自动回调 key值
    const SUBSCRIBE = await app.redis.get('expired_subscribe');
    SUBSCRIBE.send_command('config', ['set', 'notify-keyspace-events', 'Ex'],
      SubscribeExpired
    );

    function SubscribeExpired(e, r) {
      const EXPIRED_SUBKEY = '__keyevent@0__:expired';
      SUBSCRIBE.subscribe(EXPIRED_SUBKEY, () => {
        SUBSCRIBE.on('message', (chan, msg) => {
          if (msg.startsWith('goods_endAt_')) {
            const id = msg.substr('goods_endAt_'.length);
            // 更改抽奖用户为中奖用户
            ctx.model.GoodsPrizes.sum('number', {
              where: { goodsId: id },
            }).then(limit => {
              return app.model.UsersGoods.findAll({
                  attributes: ['userId'],
                  where: { goodsId: id },
                  order: [
                    ['number', 'DESC']
                  ],
                  limit: limit || 0,
                })
                .then(results => {
                  async.each(results, async (item, callback) => {
                    await app.model.UsersGoods.update({ status: 2 }, { where: { goodsId: id, userId: item.userId } });
                    callback(null);
                  });
                });
            })
            // 更改抽奖为已结束
            app.model.Goods.update({ status: 1 }, { where: { id } });
            return;
          }
          if (msg.startsWith('banner_endAt_')) {
            const id = msg.substr('banner_endAt_'.length);
            app.model.Banners.update({ status: 1 }, { where: { id } });
            return;
          }
        });
      });
    }

  });
};